package com.servlet;

import com.dao.StudentDao;
import com.entity.Student;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.util.PageUtil;
import com.util.SpringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/admin/showAllPage")
public class ShowAllPage extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pageNum = req.getParameter("pageNum");
        String pageSize = req.getParameter("pageSize");

        StudentDao studentDao = SpringUtil.getBean(StudentDao.class);
        int nums = studentDao.showNums();
        int pages=nums/Integer.parseInt(pageSize);
        if (nums%Integer.parseInt(pageSize)!=0){
            pages++;
        }
        List<Student> students = studentDao.showAllPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));

        PageUtil pageUtil = new PageUtil();
        pageUtil.setStudents(students);
        pageUtil.setPageNum(Integer.parseInt(pageNum));
        pageUtil.setPageSize(Integer.parseInt(pageSize));
        pageUtil.setPages(pages);
        pageUtil.setNums(nums);


        resp.setContentType("application/json;charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(pageUtil);

        PrintWriter writer = resp.getWriter();
        writer.write(s);
        writer.close();

    }
}
